// import ObsClient from 'esdk-obs-browserjs'

const defaultConfig = {
  ak: '4FGPVUPLKOHPYZIPTSBD',
  sk: 'm3EJB930RdGWq4lRFimnGBL1d2RrPS2FeWTWWfjJ',
  endpoint: 'obs.cn-southwest-2.myhuaweicloud.com',
  bucket: 'digital-asset',
  target: 'test'
}

export default function (setConfig = {}) {
  // 配置项
  const config: any = {}
  // 合并配置项
  Object.assign(config, defaultConfig, setConfig)

  /**
   * 获取ObsClient实例
   * @returns {ObsClient} obsClient
   * @author wangyuan
   */
  const getObsClient = () => {
    // const ak = config.ak
    // const sk = config.sk
    // return new ObsClient({
    //   access_key_id: ak,
    //   secret_access_key: sk,
    //   server: config.endpoint,
    //   timeout: 60 * 5
    // })
    return {} as any
  }

  /**
   * 获取objectKey
   * @param {*} file 文件
   * @param {*} target 目标文件夹
   * @returns {String} objectKey
   * @author wangyuan
   */
  const getKey = (file: any, target: any) => {
    const timestamp = new Date().valueOf()
    const suffix = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
    if (target) {
      return `${target}/${timestamp}${suffix}`
    } else {
      return `${timestamp}${suffix}`
    }
  }

  /**
   * 上传文件
   * @param {*} params element-plus el-upload 事件回调值
   * @param {*} target 目标文件夹
   * @returns {Promise} promise
   * @author wangyuan
   */
  const uploadFile = (params: any, target = config.target) => {
    return new Promise((resolve, reject) => {
      const bucketName = config.bucket
      const endpoint = config.endpoint
      const file = params.file
      const returner: any = {}
      const obsClient = getObsClient()
      console.log('上传文件', file)
      const key = getKey(file, target)
      console.log('object key', key)
      obsClient
        .putObject({
          Bucket: bucketName,
          Key: key,
          SourceFile: file,
          ACL: 'public-read'
        })
        .then((res: any) => {
          if (res.CommonMsg.Status < 300) {
            const url = `https://${bucketName}.${endpoint}/${key}`
            console.log('object url', url)
            returner.status = 'success'
            returner.url = url
            returner.name = file.name.substring(0, file.name.lastIndexOf('.'))
            returner.msg = '上传成功'
            returner.uid = params.file.uid
            resolve(returner)
          } else {
            returner.status = 'failure'
            returner.msg = res.CommonMsg.Message
            returner.uid = params.file.uid
            reject(returner)
          }
        })
        .catch((err: any) => {
          returner.status = 'failure'
          returner.msg = err
          returner.uid = params.file.uid
          reject(returner)
        })
    })
  }

  /**
   * 格式化html，默认给image加上style="width: 100%"属性
   * @param {*} html 原html文本
   * @returns {String}
   * @author wangyuan
   */
  const formatImage = (html: any) => {
    let pre = html
    let cur = html
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const styleIndex = pre?.indexOf('style=""')
      for (let i = styleIndex; i >= 0; i--) {
        if (pre[i] === '<') {
          const tag = `${pre[i + 1]}${pre[i + 2]}${pre[i + 3]}`
          if (tag === 'img') {
            cur = `${pre.substring(0, styleIndex)}style="width: 100%"${pre.substring(styleIndex + 8)}`
            break
          } else {
            break
          }
        }
      }
      if (cur === pre) {
        break
      } else {
        pre = cur
      }
    }
    return cur
  }

  /**
   * 格式化html，默认给video加上style="width: 100%"属性
   * @param {*} html
   * @returns {String}
   * @author wangyuan
   */
  const formatVideo = (html: any) => {
    const pre = html
    const cur = pre.replaceAll('<video controls="true">', '<video controls="true" style="width: 100%">')
    return cur
  }

  return {
    uploadFile,
    formatImage,
    formatVideo
  }
}
